/**
 * 
 */
package com.carnation.qa.socketserver.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Nick
 * 
 */
public final class FileUtil {

	public final static String UTF8 = "UTF-8";

	private final static Log log = LogFactory.getLog(FileUtil.class);

	/**
	 * 读取文本文件,默认采用utf-8
	 * 
	 * @param file
	 * @return
	 */
	public static String readTxtFile(File file) {
		return readTxtFile(file, UTF8);
	}

	/**
	 * 按照指定字符集读取文本文件
	 * 
	 * @param file
	 * @param charset
	 * @return
	 */
	public static String readTxtFile(File file, String charset) {
		StringBuilder builder = new StringBuilder();
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(new FileInputStream(
					file), charset));
			String str;
			while ((str = in.readLine()) != null) {
				builder.append(str);
				builder.append(MppContext.getNewlineSeparator());
			}
		} catch (IOException e) {
			if (log.isErrorEnabled()) {
				log.error(e);
			}
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
		}
		return builder.toString();
	}

}
